package com.zhixinglu.spring.boot.generator.nickname.controller;

import com.zhixinglu.spring.boot.generator.nickname.utils.NicknameBloomFilterGenerator;
import com.zhixinglu.spring.boot.generator.nickname.utils.NicknameGenerator;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * TestController
 * </p>
 *
 * @author weixin
 * @date 2023/3/27 11:03
 */
@Slf4j
@RestController
@RequestMapping("/redisson/")
public class TestController {

    private final RedissonClient redissonClient;

    private final NicknameGenerator nicknameGenerator;

    public TestController(NicknameGenerator nicknameGenerator, RedissonClient redissonClient) {
        this.nicknameGenerator = nicknameGenerator;
        this.redissonClient = redissonClient;
    }

    @GetMapping("generatorNickname")
    public String getGeneratorNickName(){
        long start = System.currentTimeMillis();
        String nickname = nicknameGenerator.generateNickname();
        log.info("nickname: {}, 生成时间：{}", nickname, System.currentTimeMillis() - start);
        return nickname;
    }

    @GetMapping("falsePositiveRate")
    public void falsePositiveRate(){
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("myBloomFilter");
        // 设置布隆过滤器的容量为1000，误判率为0.03
        bloomFilter.tryInit(1000, 0.03);
        // 添加1000个元素
        for (int i = 0; i < 1000; i++) {
            bloomFilter.add("element" + i);
        }
        // 检查元素是否存在于布隆过滤器中
        for (int i = 0; i < 1000; i++) {
            boolean exists = bloomFilter.contains("element" + i);
            if (!exists) {
                // 处理误判的逻辑
                System.out.println("element" + i + " may not exist in the bloom filter");
            }
        }
    }

    @GetMapping("nicknameBloomFilterGenerator")
    public String nicknameBloomFilterGenerator(){
        long start = System.currentTimeMillis();
        NicknameBloomFilterGenerator bloomFilterGenerator = new NicknameBloomFilterGenerator(redissonClient);
        String nickname = bloomFilterGenerator.generate();
        log.info("nickname: {}, 生成时间：{}", nickname, System.currentTimeMillis() - start);
        return nickname;
    }

}
